﻿using System.Threading;
using System.Web.Security;

namespace CIK.News.Web.Infrastructure.Security
{
    public class AuthenticationHttpModule : HttpModuleBase
    {
        public override void AuthenticateRequest(System.Web.HttpContext httpContext)
        {
            base.AuthenticateRequest(httpContext);

            if (httpContext != null && httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
            {
                var formsIdentity = httpContext.User.Identity as FormsIdentity;

                var token = string.Empty;
                var userName = string.Empty;
                var displayName = string.Empty;
                if (formsIdentity != null)
                {
                    var userData = new UserData(formsIdentity.Ticket.UserData);
                    userName = formsIdentity.Name;
                    displayName = userData.DisplayName;
                    token = userData.Token;
                }

                if (ValidateToken(token))
                {
                    var principal = new WebPrincipal(httpContext.User.Identity, token, userName, displayName);

                    httpContext.User = principal;
                    Thread.CurrentPrincipal = principal;
                }
                else
                {
                    LogOff();
                }
            }

        }

        /// <summary>
        /// Validate user to security service
        /// using provided token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public virtual bool ValidateToken(string token)
        {
            return true;
        }

        /// <summary>
        /// Logoff if token is not valid
        /// </summary>
        public virtual void LogOff()
        {

        }
    }
}